package mjava.lib;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;

import mjava.gc.AbstractMachine;

@SuppressWarnings("serial")
public class TdI extends HashMap<String, TdC>{
	
	public void addImportedClass(String name) {
	    try {
			this.put(name, loadImportClass(name));
		} catch (FileNotFoundException e) {
			System.err.println("Class file: " + name + ".tdc not found");
			e.printStackTrace();
		}
	}
	
	public TdC getImportedClass(String name) {
		return this.get(name);
	}
	
	public TdC loadImportClass(String className) throws FileNotFoundException{
		
		TdC tdc = null;
		try{
			FileInputStream fs = new FileInputStream(AbstractMachine.getPath() + className + ".tdc");
			ObjectInputStream os = new ObjectInputStream(fs);
			Object o = os.readObject();
			tdc = (TdC)o;
			os.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return tdc;
	}
	
	public void writeDependency(TdI tdi, String name) throws IOException {
		
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			if(!tdi.isEmpty()) {
				fos = new FileOutputStream(name + ".link");
				oos = new ObjectOutputStream(fos);
			}
		} catch (IOException e) {
			System.err.println("Can not write file: " + name + ".link");
			e.printStackTrace();
		}

		if(oos != null) {
			TdC tdc = null;
			Iterator it = (Iterator) tdi.keySet().iterator();
			
			try {
				while(it.hasNext()) {
					tdc = tdi.get(it.next());
					oos.writeObject(tdc);
				}
				oos.close();
			} catch (IOException e) {
				System.err.println("Can not write file: " + name + ".link");
				e.printStackTrace();
			}
			
		}
	}
}
